import jweixin from 'weixin-js-sdk' // 使用js-sdk
import {
  fetchH5WechatConfig,
  fetchRecordShare,
  fetchH5WechatLogin,
  fetchAuthLink,
} from '@/service/wechat-h5'
import useSystemStore from '@/store/system'
class WechatSdk {
  config: {
    appId: string
    timestamp: number
    nonceStr: string
    signature: string
    jsApiList?: jweixin.jsApiList
  }

  shareData = {
    title: '', // 分享标题
    desc: '', // 分享描述
    link: '', // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
    imgUrl: '',
  }

  status: number = 0 // 0 未初始化 1 初始化成功 2 初始化失败
  debug: boolean = false
  constructor() {}

  // 等待微信桥接并发起支付
  onBridgeReady(payParams: any, callback: (res: any) => void) {
    WeixinJSBridge.invoke('getBrandWCPayRequest', payParams, (res: any) => {
      if (res.err_msg == 'get_brand_wcpay_request:ok') {
        console.log('挑起', res)
        callback({
          ...res,
          code: 1,
        })
      } else if (res.err_msg == 'get_brand_wcpay_request:cancel') {
        console.log(`用户取消支付`, res)
        callback({
          ...res,
          code: 0,
        })
      } else {
        console.log(`支付失败`, res)
        callback({
          ...res,
          code: 2,
        })
      }
    })
  }

  setShareData(data: WechatSdk['shareData']) {
    this.shareData = data
  }

  requestPayment(payParams: any, callback: (res: any) => void) {
    // 调用微信支付
    if (typeof WeixinJSBridge === 'undefined') {
      if (document.addEventListener) {
        document.addEventListener(
          'WeixinJSBridgeReady',
          () => this.onBridgeReady(payParams, callback),
          false,
        )
      } else if (document.attachEvent) {
        document.attachEvent('WeixinJSBridgeReady', () => this.onBridgeReady(payParams, callback))
        document.attachEvent('onWeixinJSBridgeReady', () => this.onBridgeReady(payParams, callback))
      }
    } else {
      this.onBridgeReady(payParams, callback)
    }
  }

  init() {
    const sys = useSystemStore()

    if (this.status !== 1) return
    jweixin.config({
      debug: this.debug,
      ...this.config,
      jsApiList: [
        'updateTimelineShareData',
        'updateAppMessageShareData',
        'onMenuShareAppMessage',
        'onMenuShareTimeline',
        'hideMenuItems',
      ],
    })
    jweixin.ready(() => {
      this.hideMenuItems()
      this.shareFriend()
      this.shareDynamic()
    })
  }

  async hideMenuItems() {
    jweixin.hideMenuItems({
      menuList: [
        'menuItem:copyUrl',
        'menuItem:originPage',
        'menuItem:openWithSafari',
        'menuItem:openWithQQBrowser',
        'menuItem:share:email',
      ],
    })
  }

  // 分享埋点
  recordShare() {
    fetchRecordShare({})
  }

  shareFriend() {
    jweixin.updateAppMessageShareData({
      ...this.shareData,
      success: () => {
        this.recordShare()
        // 设置成功
        console.log(`分享成功`)
      },
    })
    jweixin.onMenuShareAppMessage({
      ...this.shareData,
      success: () => {
        this.recordShare()
        console.log('分享成功 onMenuShareAppMessage')
      },
      fail: (err1) => {
        console.log('分享失败', err1)
      },
      cancel: () => {
        console.log('取消分享')
      },
    })
  }

  // 分享朋友圈
  shareDynamic() {
    jweixin.updateTimelineShareData({
      ...this.shareData,
      success: () => {
        console.log(`分享朋友圈成功`)
        // 设置成功
      },
    })

    jweixin.onMenuShareTimeline({
      ...this.shareData,
      success: () => {
        this.recordShare()
        console.log('分享成功 onMenuShareTimeline')
      },
      fail: (err1) => {
        console.log('分享失败', err1)
      },
      cancel: () => {
        console.log('取消分享')
      },
    })
  }

  async getConfig() {
    try {
      if (!this.config) {
        const res = await fetchH5WechatConfig({
          url: encodeURIComponent(location.href.split('#')[0]),
        })
        const { title, content, imgUrl, ...config } = res.data
        wxSdk.setConfig(config)
      }
    } catch (err) {
      console.log(err, '获取配置失败')
    }
  }

  setConfig(config: WechatSdk['config']) {
    this.status = 1
    this.config = config
  }

  getUrlParams(url: string) {
    const i = url.indexOf('?')
    const params = new URLSearchParams(url.substring(i + 1))
    return params
  }

  splitUrl(v: string, f = '#/') {
    if (!v) return v

    return String(v).split(f)[0]
  }

  // 获取回调地址的code
  getUrlCode(url: string) {
    const params = this.getUrlParams(url)
    return params.get('code') || ''
  }

  authLogin() {
    return new Promise(async (resolve, reject) => {
      const href = this.splitUrl(location.href, '#')
      const code = this.getUrlCode(href)
      try {
        if (code) {
          // 使用 URL 对象解析链接g
          // 提取查询参数
          const loginInfo = await fetchH5WechatLogin({ code })
          resolve(loginInfo)
        } else {
          const r = await fetchAuthLink({})
          // let href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect\_uri=${encodeURIComponent(originHref)}&response\_type=code&scope=snsapi\_userinfo&state=1#wechat\_redirect=1`
          const { authUrl } = r.data

          window.location.href = authUrl
        }
      } catch (err) {
        reject(err)
      }
    })
  }

  onError() {
    return new Promise((resolve, reject) => {
      jweixin.error((err) => {
        this.status = 2
        console.log('微信sdk错误', err)
        resolve(err)
      })
    })
  }
}

export const wxSdk = new WechatSdk()
